package com.cjack.frenchexcel.service;

import com.cjack.frenchexcel.dao.CooperativeNumberDao;
import com.cjack.frenchexcel.dao.DepanPersoDao;
import com.cjack.frenchexcel.dao.UserDao;
import com.cjack.frenchexcel.model.DepanRersoModel;
import com.cjack.frenchexcel.table.CooperativeNumberTable;
import com.cjack.frenchexcel.table.DepanPersoTable;
import com.cjack.frenchexcel.util.ModelUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import java.text.DecimalFormat;
import java.util.List;

@Service
public class DepanPersoService {

    @Autowired
    private DepanPersoDao dao;
    @Autowired
    private UserDao userDao;
    @Autowired
    private CooperativeNumberDao cooperativeNumberDao;


    public List<DepanRersoModel> list( DepanRersoModel model){
        Sort sort = new Sort( Sort.Direction.DESC, "createTime");
        Example< DepanPersoTable> example = Example.of( ModelUtils.copySignModel( model, DepanPersoTable.class));
        return ModelUtils.copyListModel( dao.findAll( example, sort), DepanRersoModel.class);
    }

    public void save( DepanRersoModel model) throws Exception {
        DepanPersoTable table;
        if( !StringUtils.isEmpty( model.getJobNumber())) {
            model.setUserId(userDao.getOneByJobNumber(model.getJobNumber()).getId());
        }
        if( model.getId() == null){//新增，把model里面的属性全部复制到新的table里面
            table = ModelUtils.copySignModel( model, DepanPersoTable.class);
        }else{//修改，把model里面的[非空]属性赋值到数据库里面查询的table里面
            table = dao.findOne( model.getId());
            ModelUtils.copySignModel( model, table);
        }
        DecimalFormat df = new DecimalFormat("#.00");
        if( !StringUtils.isEmpty( model.getMontant())){
            table.setMontant( Double.valueOf( df.format( model.getMontant())));
        }
        if( model.getCooperativeNumber() != null){
            //如果供应商编号不存在，返回错误
            CooperativeNumberTable cooperativeNumberTable = cooperativeNumberDao.getByNumber( model.getCooperativeNumber());
            if( cooperativeNumberTable == null){
                throw new Exception( "供应商编号不存在");
            }
            table.setCooperativeName( cooperativeNumberTable.getName());
            table.setCooperativeNumber( cooperativeNumberTable.getNumber());
        }
        dao.save( table);
    }
}
